package com.bdqn.controller;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * IndexController
 *
 * @author LILIBO
 * @since 2023-02-18
 */
@Controller
public class IndexController {

    @Resource
    private UserService userService;

    @GetMapping("/hello")
    public String toHello(Model model, HttpServletRequest request, HttpSession session) {
        model.addAttribute("msg", "你好，世界！");
        User user = userService.getById(1L);
        model.addAttribute("date",new Date());
        model.addAttribute("sex", "woman");
        model.addAttribute("user", user);
        request.setAttribute("test","这是Request中的值");
        session.setAttribute("test","这是Session中的值");
        List<User> users = userService.list();
        model.addAttribute("users", users);
        return "demo/hello";
    }

    @GetMapping("/test")
    public String toTest(Model model, @RequestParam(required = false) Integer id) {
        model.addAttribute("id", id);
        return "demo/test";
    }

    @GetMapping("/layout")
    public String toLayout() {
        return "demo/layout";
    }


    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(Model model, HttpSession session, User user) {
        if (user == null) {
            model.addAttribute("msg", "参数错误，请重试！");
            return "login";
        }
        if (!"aaa".equals(user.getUsrName()) || !"888".equals(user.getUsrPassword())) {
            model.addAttribute("msg", "账号或密码错误，请重试！");
            return "login";
        }
        // 登录成功
        session.setAttribute("loginUser", user);
        return "main";
    }

    @RequestMapping("/logout")
    public String doLogout(HttpSession session) {
        session.invalidate();
        return "login";
    }

    @GetMapping("/main")
    public String toMain() {
        return "main";
    }
}
